/**
 * 
 */
package net.phoenix.repository;

import javax.jcr.NamespaceException;
import javax.jcr.NamespaceRegistry;
import javax.jcr.RepositoryException;

/**
 * @author lixf
 *
 */
public abstract class NamespacedSession extends GeneralSession implements NameResolver{
	private NamespaceRegistry namespaces;
	public NamespacedSession(NamespaceRegistry namespaces){
		this.namespaces = namespaces;
	}
	
	@Override
	public void setNamespacePrefix(String prefix, String uri) throws NamespaceException, RepositoryException {
		namespaces.registerNamespace(prefix, uri);
	}

	@Override
	public String[] getNamespacePrefixes() throws RepositoryException {
		return namespaces.getPrefixes();
	}

	@Override
	public String getNamespaceURI(String prefix) throws NamespaceException, RepositoryException {
		return namespaces.getURI(prefix);
	}

	@Override
	public String getNamespacePrefix(String uri) throws NamespaceException, RepositoryException {
		return namespaces.getPrefix(uri);
	}
	
	@Override
	public Name parseName(String name) throws NamespaceException, RepositoryException{
		if(name.startsWith("{")){
			int pos = name.indexOf('}');
			String url = name.substring(1, pos);
			String local = name.substring(pos+1);
			return new BasicName(url, this.getNamespacePrefix(url), local);
		}else{
			int pos = name.indexOf(':');
			if(pos>0){
				String prefix = name.substring(0,pos);
				String local = name.substring(pos+1);
				return new BasicName(this.getNamespaceURI(prefix),prefix, local);
			}
		}
		return new BasicName(null,null,name);
	}
	

}
